package com.example.assignment01_javaee.Service.Impl;

import com.example.assignment01_javaee.Entity.Inventory;
import com.example.assignment01_javaee.Entity.Order;
import com.example.assignment01_javaee.Dao.OrderDao;

import com.example.assignment01_javaee.Service.InventoryService;
import com.example.assignment01_javaee.Service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    InventoryService inventoryService;
    //查询所有的order
    @Override
    public List<Order> getAllOrders(){
        return orderDao.getAllOrders();
    }

    //根据order id查找
    @Override
    public Order getOrderById(int orderId){

        return orderDao.getOrderById(orderId);
    }

    //增加order
    @Override
    public String createOrder(Order order){
        String result = "";
        Inventory inventory = inventoryService.getInventoryByProductId(order.getProduct().getProductId());
        if(inventory != null){
            if(order.getCount() < inventory.getQuantity()){
                orderDao.createOrder(order);
                result = "订单创建成功！";
            }else{
                result = "订单创建失败！库存不足！";
            }
        }
        return result;
    }

    //修改下单数量
    public String updateOrder(int orderId,int count){
        int product_id = orderDao.getOrderById(orderId).getProduct().getProductId();
        Inventory inventory = inventoryService.getInventoryByProductId(product_id);
        Map<String,Integer> map = new HashMap<>();
        if(inventory.getQuantity() >= count){
            map.put("orderId",orderId);
            map.put("count",count);

            orderDao.updateOrder(map);
            return "更新成功！";
        }
        return "库存不足！";
    }

    //根据order id删除
    @Override
    public void deleteOrder(int orderId){

        orderDao.deleteOrder(orderId);
    }
}
